import React, { useEffect, useState } from 'react'
import type { ChangeEvent } from 'react'
import { Input } from 'antd'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { LIST_SEARCH_PARAM_KEY } from '../constant'

const { Search } = Input

const ListSearch: React.FC = () => {
  const nav = useNavigate()
  const { pathname } = useLocation()
  const [searchParams] = useSearchParams()
  const [value, setValue] = useState<string>('')

  useEffect(() => {
    const curVal = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''
    setValue(curVal)
  }, [searchParams])

  function handleChange(e: ChangeEvent<HTMLInputElement>) {
    setValue(e.target.value)
  }
  function handleSearch(val: string) {
    // 改变 url，兼容用户刷新操作
    nav({ pathname, search: `${LIST_SEARCH_PARAM_KEY}=${val}` })
  }
  return (
    <Search
      allowClear
      onSearch={handleSearch}
      onChange={handleChange}
      value={value}
      size="large"
      style={{ width: '260px' }}
    />
  )
}

export default ListSearch
